package com.liangjie.jdbc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JDBC extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		PrintWriter pw = resp.getWriter();
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager
					.getConnection("jdbc:mysql://localhost/test?user=root&password=liangjie");
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("select * from article");
			pw.print("<html><body><table width = '600' height = '300' border = '2'>");
			pw.print("<tr><td>ID</td><td>PID</td><td>RootID</td><td>Title</td><td>Content</td><td>PDate</td><td>IsLeaf</td></tr>");
			while (rs.next()) {
				pw.print("<tr>");
				pw.print("<td>");
				pw.print(rs.getString(1));
				pw.print("</td>");
				pw.print("<td>");
				pw.print(rs.getString(2));
				pw.print("</td>");
				pw.print("<td>");
				pw.print(rs.getString(3));
				pw.print("</td>");
				pw.print("<td>");
				pw.print(rs.getString(4));
				pw.print("</td>");
				pw.print("<td>");
				pw.print(rs.getString(5));
				pw.print("</td>");
				pw.print("<td>");
				pw.print(rs.getString(6));
				pw.print("</td>");
				pw.print("<td>");
				pw.print(rs.getString(7));
				pw.print("</td>");
				pw.print("</tr>");
			}
			rs.close();
			stmt.close();
			conn.close();
			pw.flush();
			pw.print("</table></body><html>");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
